package com.design.mediatorPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * <h1>中介者模式</h1>
 * 聊天室，用户列表，发送消息
 */
public class ChatRoomDemo {
    public static void main(String[] args) {
        ChatRoom chatRoom = new ChatRoomConcrete();
        UserConcrete tom = new UserConcrete("tom", chatRoom);
        UserConcrete jerry = new UserConcrete("jerry", chatRoom);
        UserConcrete dog = new UserConcrete("dog", chatRoom);
        chatRoom.addUser(dog);
        chatRoom.addUser(tom);
        chatRoom.addUser(jerry);
        tom.sendMessage("hi");
        jerry.sendMessage("hello");
    }
}


/**
 * <h1>抽象中介者</h1>
 */
interface ChatRoom {
    void addUser(User user);
    void sendMessage(String message, User user);
}

/**
 * <h1>具体中介者：聊天室</h1>
 * 聊天室，负责用户列表的维护，发送消息
 */
class ChatRoomConcrete implements ChatRoom {
    private int count;
    private List<User> users = new ArrayList<>();

    /*
    * 加入聊天室，用户列表增加用户
     */
    @Override
    public void addUser(User user) {
        users.add(user);
        count++;
        System.out.println("用户" + user.name + "加入聊天室");
    }
    /*
    * 发送消息，遍历用户列表，发送给除了发送者以外的用户
     */
    @Override
    public void sendMessage(String message, User user) {
        for (User u : users) {
            if (u != user) {
                u.receive(message);
            }
        }
    }
}

/**
 * <h1>抽象同事</h1>
 * 用户，负责发送消息，接收消息
 */
abstract class User {
    String name;
    ChatRoom chatRoom;
    public User(String name, ChatRoom chatRoom) {
        this.name = name;
        this.chatRoom = chatRoom;
    }
    abstract void receive(String message);

}

/**
 * <h1>具体同事</h1>
 */
class UserConcrete extends User {
    public UserConcrete(String name, ChatRoom chatRoom) {
        super(name, chatRoom);
    }
    // 调用 中介者 发送消息
    public void sendMessage(String message) {
        chatRoom.sendMessage(message, this);
    }
    @Override
    void receive(String message) {
        System.out.println(this.name + "收到消息：" + message);
    }
}
